package com.effectiv.crm.service.impl;

import java.lang.reflect.Field;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import jodd.bean.BeanUtil;
import jodd.util.ReflectUtil;
import jodd.util.StringUtil;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Update;

import lombok.extern.slf4j.Slf4j;

import com.effectiv.crm.domain.Contact;
import com.effectiv.crm.repository.ContactRepository;
import com.effectiv.crm.service.api.ContactService;
import static org.springframework.data.mongodb.core.query.Criteria.where;  
import static org.springframework.data.mongodb.core.query.Query.query;  
 

@Slf4j
@Named
public class ContactServiceImpl implements ContactService {

	@Inject
	private ContactRepository repository;

	@Inject
	private MongoTemplate template;

	private String ignoreFields[] = { "serialVersionUID", "id", "version",
			"createdDate", "lastModifiedDate", "createdBy", "lastModifiedBy" };

	public void save(Contact contact) {
		log.debug("Contact is being saved - {}", contact);
		repository.save(contact);
	}

	public void update(Contact contact) {
		// TODO - Cache reflected fields
		Field fields[] = ReflectUtil.getAccessibleFields(Contact.class);

		String fieldName = null;

		Update u = new Update();

		for (Field f : fields) {
			fieldName = f.getName();
			if (StringUtil.equalsOne(fieldName, ignoreFields) == -1) {
				u.set(fieldName, BeanUtil.getPropertySilently(contact, fieldName));
			}
		}

		template.updateFirst(query(where("id").is(contact.getId())), u, Contact.class);

	}

	public List<Contact> findAll() {
		return repository.findAll();
	}

	public Contact findOne(String id) {
		return repository.findOne(id);
	}

	public void delete(Contact contact) {
		Update u = new Update();
		u.set("deleted", true);
		template.updateFirst(query(where("id").is(contact.getId()) ), u, Contact.class);

	}

	@Override
	public List<Contact> findByDeleted(boolean deleted) {
		return repository.findByDeleted(deleted);
	}

}
